<template>
  <div>
    <div v-if="isShowLoginModal" @click="clickBg" class="bg"></div>
    <van-dialog
      confirm-button-text="登录"
      class="dialog"
      :close-on-click-overlay="true"
      :overlay="false"
      :show-cancel-button="false"
      theme="round-button"
      @confirm="loginFn"
      :value="isShowLoginModal"
    >
      <van-field v-model.trim="username" type="text" label="用户名" />
      <!-- 输入密码 -->
      <van-field v-model.trim="password" type="password" label="密码" />
    </van-dialog>
  </div>
</template>
<script>
import { userLoginAPI } from "@/request/api";
export default {
  data() {
    return {
      username: "",
      password: "",
    };
  },
  props: ["isShowLoginModal"],
  methods: {
    //点击遮罩层
    clickBg() {
      this.$emit("showLoginModal", false);
    },
    //登录按钮逻辑
    async loginFn() {
      if (!this.username) {
        this.$notify({ type: "danger", message: "账号不能为空" });
        return;
      }
      if (!this.password) {
        this.$notify({ type: "danger", message: "密码不能为空" });
        return;
      }

      let res = await userLoginAPI({
        username: this.username,
        password: this.password,
      });
      if (res.errno == 602) {
        this.password = "";
        this.$notify({
          type: "danger",
          message: "密码错误",
        });
        return;
      }
      if (res.errno == 0) {
        this.$notify({
          type: "success",
          message: "登录成功",
        });
      }
      localStorage.setItem("token", res.data.token);
      localStorage.setItem("userInfo", JSON.stringify(res.data.userInfo));
      this.username = "";
      this.password = "";
      //关闭模态框
      this.$emit("showLoginModal", false);
      this.$emit("getUserInfo", res.data.userInfo);
    },
  },
};
</script>

<style lang="less" scoped>
.bg {
  top: 0;
  left: 0;
  z-index: 999;
  position: absolute;
  width: 100%;
  height: 100%;
  background-color: rgba(5, 5, 5, 0.365);
}
.dialog {
  padding: 0.3rem;
  width: 70%;
}
</style>
